package com.liujit.common.utils;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.enums.SqlKeyword;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liujit.common.domain.query.PageQuery;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: liujun
 * @date: 2021/6/16 10:19 上午
 * @description: 分页工具类
 */
public class Pagination implements Serializable {

    private static final long serialVersionUID = -7464287269436808199L;

    /**
     * 排序方式
     */
    private static final String ASC = "asc";

    /**
     * 当前页码
     */
    private static final int CURR_PAGE = 1;

    /**
     * 每页条数
     */
    private static final int LIMIT = 10;

    public static <T> Page<T> page(PageQuery query) {
        if (query.getPageNumber() == null) {
            query.setPageNumber(CURR_PAGE);
        }
        if (query.getPageSize() == null) {
            query.setPageSize(LIMIT);
        }
        // mybatis-plus分页参数
        Page<T> page = new Page<>(query.getPageNumber(), query.getPageSize());
        // 排序
        if (StrUtil.isNotBlank(query.getSortName()) && StrUtil.isNotBlank(query.getSortOrder())) {
            List<OrderItem> orders = new ArrayList<>();
            orders.add(new OrderItem() {{
                setColumn(query.getSortName());
                setAsc(SqlKeyword.ASC.getSqlSegment().equals(query.getSortOrder()));
            }});
            page.setOrders(orders);
        }
        return page;
    }
}
